package com.tang.controller;


import com.tang.dto.CategoryDTO;
import com.tang.resp.JsonResp;
import com.tang.service.impl.CategoryServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/category/*")
public class CategoryController {
    @Autowired
    private CategoryServiceImpl categoryService;
    @GetMapping("all")
    public JsonResp all(){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        resp.setMessage("查询分类成功");
        List<CategoryDTO> all = categoryService.all();
        resp.setData(all);
        return resp;
    }
    @Validated
    @GetMapping("list")
    public JsonResp list(String name, @NotNull int pageNum, @NotNull int pageSize){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        resp.setMessage("查询分类成功");
        Map<String, Object> map = categoryService.list(name,pageNum, pageSize);
        resp.setData(map);
        return resp;
    }
    @GetMapping("listChildren")
    public JsonResp listChildren(String id){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        List<CategoryDTO> dtos = categoryService.listChildren(id);
        if (ObjectUtils.isNotEmpty(dtos)){
            resp.setMessage("查询子分类成功");
        }else {
            resp.setMessage("查询子分类失败,当前分类可能无子分类");
        }
        resp.setData(dtos);
        return resp;
    }
    @PostMapping("update")
    public JsonResp update(@RequestBody CategoryDTO categoryDTO){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        int update = categoryService.update(categoryDTO);
        if (update>0){
            resp.setMessage("更新分类成功");
        }else {
            resp.setMessage("更新分类失败");
        }
        resp.setData(update);
        return resp;
    }
    @DeleteMapping("delete/{id}")
    public JsonResp delete(@PathVariable("id") String id){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        int delete = categoryService.delete(id);
        if (delete>0){
            resp.setMessage("删除分类成功");
        }else {
            resp.setMessage("删除分类失败");
        }
        resp.setData(delete);
        return resp;
    }
}
